/*
 * 仪器→资产项目
 */
public with sharing class AssetProjectController
{
    //获取仪器所有的资产项目
    public List<AssetProjectBean> apList{get;set;}
    //资产项目对象 视图使用放大镜的时候会使用到
    public AssetProject__c ap{get;set;}
    //仪器id
    public String eId{get;set;}
    //获取仪器的资产项目列表  显示出来
    public List<AssetProject__c> oldList{get;set;}
    public String dataJson {get;set;}

    public Boolean isSuccess {get;set;}//是否成功
    public AssetProjectController(ApexPages.StandardController stdController)
    {
        //获得仪器id
        eId = System.currentPageReference().getParameters().get('id');
        apList=new List<AssetProjectBean>();
        ap=new AssetProject__c();
        //ap.Instrument__c=eId;
        isSuccess =false;
    }

   
    
    public void init(){
        this.getOldList();
        this.getAPList();
    }
    
    //获得已经保存的数据
    public void getOldList(){
        if (String.isBlank(eId) == false){
            Schema.DescribeSobjectResult m = AssetProject__c.sObjectType.getDescribe();
            Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();
            
            String sql = 'select ';
            String fields = '';
            for (String field : fieldMap.keySet()) {
                if (fields.length() > 0) {
                    fields += ', '; 
                }
                fields += field;
            }
            sql += fields;
            sql += ' from AssetProject__c where Instrument__c= \'' + eId+ '\'';
            oldList=Database.query(sql);

        }
    }
    
    //获得该仪器所有的产品
    public void getAPList(){
        System.debug('===========================getAPList');
        //Supplier__c,Account__c
      List<Product__c> eqList=[select Id, Name,Category1__c,Category2__c from Product__c where Id=:eId];
        if(eqList.size()>0){
            Product__c product=eqList[0];//获得产品
            
            String [] arr = product.Category2__c.split('-',2);
            String category2='%'+arr[0]+'-%';
            
            //根据产品获得试剂项目
            //2017-03-07修改如下
            System.debug('==========='+category2);
            List<ProductProject__c> ppList=[select Name,Id from ProductProject__c where (ThirdClassification__c='试剂' or ThirdClassification__c='试纸') 
                                            and PrimaryClassification__c=:product.Category1__c
                                            and SecondClassification__c like :category2];
            
            /*
            String bId='';
            List<Brand__c> bList=[select Name,Id from Brand__c where Name=:eq.Brand__c limit 1];
            if(bList.size()>0){
                bId=bList[0].Id;
            }*/
          
            for(ProductProject__c pp:ppList){
                Boolean flag = false;
               AssetProjectBean apb=new AssetProjectBean();
               apb.rec.Name=pp.Name;
               apb.rec.ProductProject__c=pp.Id;
              // apb.rec.Instrument__c=eId;
              // apb.rec.Supplier__c=eq.Supplier__c;
              // apb.rec.Account__c=eq.Account__c;
               //把该仪器存在的数据 返回 赋值
               for(AssetProject__c old:oldList){
                   if(pp.Id==old.ProductProject__c){
                       flag = true;
                      // apb.rec.MonthlySampleAmount__c =old.MonthlySampleAmount__c;
                      // apb.rec.AnnualBuyTotalPrice__c =old.AnnualBuyTotalPrice__c;
                      // apb.rec.Supplier__c =old.Supplier__c;

                      // apb.rec.SinglePackageAmount__c =old.SinglePackageAmount__c;
                       apb.rec.SinglePackageDimension__c =old.SinglePackageDimension__c;
                      // apb.rec.SinglePackagePrice__c =old.SinglePackagePrice__c;
                       apb.rec.IsJoinQualityEvaluation__c =old.IsJoinQualityEvaluation__c;
                       apb.rec.IndoorQualityControlBrand__c =old.IndoorQualityControlBrand__c;
                       apb.rec.Brand__c=old.Brand__c;
                       //apb.rec.ReagentSupplier__c = old.ReagentSupplier__c;

                       apb.rec.SampleAmount__c = old.SampleAmount__c;
                       apb.rec.Calibrator__c = old.Calibrator__c;
                       apb.rec.QualityProducts__c = old.QualityProducts__c;

                       apb.rec.PriceML__c = old.PriceML__c;
                       apb.rec.PriceCS__c = old.PriceCS__c;
                       apb.rec.IsJoinWEvaluation__c = old.IsJoinWEvaluation__c;


                      // apb.UnitPrice =old.UnitPrice__c;
                      // apb.StatisticalYear=old.StatisticalYear__c;
                       apb.chk=true;
                       apb.selected=true;
                   }
                   
               }
               
               apList.add(apb);
             
               /*
               apb.rec.Brand__c=pp.Brand__c;
               if(String.isBlank(bId)==false){
                   apb.rec.Brand_c=bId;
               }*/
              
               //System.Debug('项目名称：'+pp.Name+'----品牌：'+pp.Brand__c+'----二级分类：'+pp.Category2__c);
               /*  
                  //System.Debug('仪器名称：'+eq.Name+'----项目ID：'+eq.Product__c);
                  List<Product__c> productList=[select Name,Category2__c from Product__c where Id=:eq.Product__c];
                  if(productList.size()>0){
                  Product__c product=productList[0];
            
               }*/
            }
          
        }
    }
    
    //保存
    public void save() {
      System.debug('AssetProjectController==>');
        Savepoint sp = Database.setSavepoint();
        try {
            //删除该仪器下所有的资产项目
            List<AssetProject__c> delList = [select Id from AssetProject__c where Instrument__c= :eId];
            if (delList.size() > 0) delete delList;
            
            // 插入已选择的物品
            if (apList.size() > 0) {
                List<AssetProject__c> insList = new List<AssetProject__c>();
                for (AssetProjectBean apb : apList) {
                    if(apb.selected){
                     insList.add(
                        new AssetProject__c(
                            Name = apb.rec.Name, //试剂名称
                            Brand__c =apb.rec.Brand__c, //品牌
                            //MonthlySampleAmount__c =apb.rec.MonthlySampleAmount__c,
                            //AnnualBuyTotalPrice__c =apb.rec.AnnualBuyTotalPrice__c,
                            Supplier__c = apb.rec.Supplier__c,
                            //SinglePackageAmount__c =apb.rec.SinglePackageAmount__c,
                            SinglePackageDimension__c = apb.rec.SinglePackageDimension__c,
                            SinglePackagePrice__c = apb.rec.SinglePackagePrice__c,
                            //UnitPrice__c = '',
                            IsJoinQualityEvaluation__c = apb.rec.IsJoinQualityEvaluation__c,
                            IndoorQualityControlBrand__c = apb.rec.IndoorQualityControlBrand__c,
                            ProductProject__c = apb.rec.ProductProject__c,
                           // Instrument__c = apb.rec.Instrument__c,
                            //ReagentSupplier__c = apb.rec.ReagentSupplier__c,

                            SampleAmount__c = apb.rec.SampleAmount__c,
                            Calibrator__c = apb.rec.Calibrator__c,
                            QualityProducts__c = apb.rec.QualityProducts__c,

                            PriceML__c = apb.rec.PriceML__c,
                            PriceCS__c = apb.rec.PriceCS__c,
                            IsJoinWEvaluation__c = apb.rec.IsJoinWEvaluation__c,

                            Account__c =apb.rec.Account__c
                        )
                      );
                    }
                }
                
                insert insList;
            }
            isSuccess = true;
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, System.Label.Save_OK));
        } catch (Exception e) {
            Database.rollback(sp);
            isSuccess = false;
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, e.getMessage()));
        }
    }
    
    public class AssetProjectBean{
        public AssetProject__c rec{get;set;}
        public Decimal UnitPrice{get;set;} //单位价
        public String StatisticalYear{get;set;} //统计年度
        public Boolean chk{get;set;}
        public Boolean selected{get;set;}//选中保存项

        public AssetProjectBean() {
            rec=new AssetProject__c();
        }
    }
}